﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;

namespace ClipboardUrlMonitor
{
    public partial class MainForm : Form
    {
        // 组件声明
        private NotifyIcon trayIcon;
        private System.Windows.Forms.Timer clipboardTimer;
        private HttpClient _httpClient;
        private string lastClipboardContent = string.Empty;

        // 正则表达式预编译
        private static readonly Regex UrlValidationRegex = new Regex(
            @"^(https?|ftp)://[^\s/$.?#].[^\s]*$",
            RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private static readonly Regex TitleExtractRegex = new Regex(
            @"<title[^>]*>(.*?)</title>",
            RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);

        private static readonly Regex ImageExtractRegex = new Regex(
            @"<img[^>]+src=\""([^""]+)\""",
            RegexOptions.IgnoreCase | RegexOptions.Compiled);

        // 新增内容分析组件
        private static readonly Regex CleanRegex = new Regex(@"\s+", RegexOptions.Compiled);
        private const int SummaryLength = 200;

        private string GenerateSummary(HtmlAgilityPack.HtmlDocument doc)
        {
            try
            {
                // 智能正文提取算法
                var textNodes = doc.DocumentNode.SelectNodes("//p|//div[contains(@class, 'content')]");

                if (textNodes == null) return "未找到正文内容";

                var cleanText = string.Join("\n", textNodes
                    .Select(n => CleanRegex.Replace(n.InnerText.Trim(), " "))
                    .Where(t => t.Length > 20));

                return cleanText.Length > SummaryLength
                    ? cleanText.Substring(0, SummaryLength) + "..."
                    : cleanText;
            }
            catch
            {
                return "内容解析失败";
            }
        }

        public MainForm()
        {
            InitializeComponent();
            InitializeHttpClient();
            InitializeTrayIcon();
            InitializeTimer();
            this.Visible = false;
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            SuspendLayout();
            // 
            // MainForm
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(1, 1);
            ControlBox = false;
            FormBorderStyle = FormBorderStyle.None;
            Icon = (Icon)resources.GetObject("$this.Icon");
            Margin = new Padding(4, 4, 4, 4);
            MaximizeBox = false;
            MinimizeBox = false;
            Name = "MainForm";
            ShowIcon = false;
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.Manual;
            ResumeLayout(false);
        }

        private void InitializeHttpClient()
        {
            _httpClient = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                UseCookies = false
            })
            {
                Timeout = TimeSpan.FromSeconds(8),
                DefaultRequestHeaders =
                {
                    {"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"},
                    {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"},
                    {"Accept-Encoding", "gzip, deflate"}
                }
            };
        }
        //在以下代码中对trayIcon对像加图标
        private void InitializeTrayIcon()
        {
            trayIcon = new NotifyIcon
            {
                Icon = SystemIcons.Application,
                Text = "优哥书签",
                Visible = true,
                ContextMenuStrip = CreateContextMenu()
            };

            var app = Properties.Resources.app;
            using (var stream = new System.IO.MemoryStream(app))
            {
                trayIcon.Icon = new Icon(stream, SystemInformation.SmallIconSize);
            }

            trayIcon.DoubleClick += (s, e) => ShowConfiguration();

            // 添加图标释放处理
            this.Disposed += (s, e) => trayIcon.Icon?.Dispose();
        }

        private ContextMenuStrip CreateContextMenu()
        {
            var menu = new ContextMenuStrip();

            var configItem = new ToolStripMenuItem("配置");
            configItem.Click += (s, e) => ShowConfiguration();

            var logItem = new ToolStripMenuItem("查看日志");
            logItem.Click += (s, e) => ShowLogViewer();

            var exitItem = new ToolStripMenuItem("退出");
            exitItem.Click += (s, e) => Application.Exit();

            menu.Items.AddRange(new ToolStripItem[] { configItem, logItem, new ToolStripSeparator(), exitItem });
            return menu;
        }

        private void InitializeTimer()
        {
            clipboardTimer = new System.Windows.Forms.Timer
            {
                Interval = 800
            };
            clipboardTimer.Tick += async (s, e) => await CheckClipboardAsync();
            clipboardTimer.Start();
        }

        private async Task CheckClipboardAsync()
        {
            try
            {
                if (!Clipboard.ContainsText()) return;

                string currentText = Clipboard.GetText().Trim();
                if (currentText == lastClipboardContent || !IsValidUrl(currentText)) return;

                lastClipboardContent = currentText;
                var /*(title, imageUrl)*/wc = await ExtractWebContentAsync(currentText);
                ShowContentNotification(/*currentText, title, imageUrl*/wc);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[Error] {DateTime.Now:HH:mm:ss} - {ex.Message}");
            }
        }

        private bool IsValidUrl(string input)
        {
            return !string.IsNullOrWhiteSpace(input)
                && UrlValidationRegex.IsMatch(input)
                && Uri.TryCreate(input, UriKind.Absolute, out _);
        }

        //private async Task<(string Title, string ImageUrl)> ExtractWebContentAsync(string url)
        //{
        //    try
        //    {
        //        using var response = await _httpClient.GetAsync(url);
        //        response.EnsureSuccessStatusCode();

        //        string html = await response.Content.ReadAsStringAsync();
        //        return (
        //            ExtractPageTitle(html),
        //            ExtractFirstImageUrl(html, url)
        //        );
        //    }
        //    catch (TaskCanceledException)
        //    {
        //        return ("请求超时", "未获取");
        //    }
        //    catch (HttpRequestException hex)
        //    {
        //        return ($"HTTP错误: {hex.StatusCode}", "无法加载");
        //    }
        //}

        private async Task<WebContent> ExtractWebContentAsync(string url)
        {
            try
            {
                using var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var html = await response.Content.ReadAsStringAsync();
                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(html);

                return new WebContent(
                    ExtractPageTitle(html),
                    ExtractFirstImageUrl(html, url),
                    GenerateSummary(doc),
                    url
                );
            }
            catch
            {
                return WebContent.Error;
            }
        }

        private string ExtractPageTitle(string html)
        {
            var match = TitleExtractRegex.Match(html);
            return match.Success ?
                WebUtility.HtmlDecode(match.Groups[1].Value).Trim()
                : "无标题";
        }

        private string ExtractFirstImageUrl(string html, string baseUrl)
        {
            var match = ImageExtractRegex.Match(html);
            if (!match.Success) return "未找到图片";

            try
            {
                var imageUrl = WebUtility.HtmlDecode(match.Groups[1].Value);
                return Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute)
                    ? imageUrl
                    : new Uri(new Uri(baseUrl), imageUrl).AbsoluteUri;
            }
            catch
            {
                return "无效图片地址";
            }
        }

        //private void ShowContentNotification(string url, string title, string imageUrl)
        //{
        //    if (InvokeRequired)
        //    {
        //        Invoke(new Action(() => ShowContentNotification(url, title, imageUrl)));
        //        return;
        //    }

        //    this.ShowContentNotification2(url, title, imageUrl);

        //    var message = new StringBuilder()
        //        .AppendLine($"🕸 检测到新网页内容")
        //        .AppendLine($"🔗 URL: {url}")
        //        .AppendLine($"📌 标题: {title}")
        //        .AppendLine($"🖼 首图: {(imageUrl.Length > 50 ? imageUrl.Substring(0, 50) + "..." : imageUrl)}")
        //        .ToString();

        //    trayIcon.ShowBalloonTip(5000, "网页内容分析", message, ToolTipIcon.Info);
        //}

        private void ShowContentNotification(WebContent content)
        {
            this.ShowContentNotification2(content.Url, content.Title, content.ImageUrl, content.Summary);
            var message = new StringBuilder()
                .AppendLine($"📌 标题: {content.Title}")
                .AppendLine($"🌐 地址: {content.Url}")
                .AppendLine($"📷 首图: {content.ImageUrl}")
                .AppendLine($"📝 摘要: {content.Summary}")
                .ToString();

            trayIcon.ShowBalloonTip(5000, "网页内容分析", message, ToolTipIcon.Info);
            // 显示到通知窗口或MessageBox
            //notificationForm.UpdateContent(content);
            //MessageBox.Show(message);
        }

        private void ShowContentNotification2(string url, string title, string imageUrl, string summary)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => ShowContentNotification2(url, title, imageUrl, summary)));
                return;
            }

            // 创建并显示提示窗体
            var notification = new NotificationForm(url, title, imageUrl, summary)
            {
                TopLevel = true,
                Owner = this
            };
            notification.Show();
        }


        private void ShowConfiguration()
        {
            // 配置窗体实现留空
            MessageBox.Show("配置功能待实现", "系统提示",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ShowLogViewer()
        {
            // 日志查看器实现留空
            MessageBox.Show("日志功能待实现", "系统提示",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _httpClient?.Dispose();
                clipboardTimer?.Stop();
                trayIcon?.Dispose();
            }
            base.Dispose(disposing);
        }




    }

    public record WebContent(
    string Title,
    string ImageUrl,
    string Summary,
    string Url)
    {
        public static WebContent Error => new(
            "内容获取失败",
            string.Empty,
            "无法加载网页内容",
            string.Empty);
    }
}
